import { FSMControl } from "../fsm/FSMControl";
import { FSMState } from "../fsm/State";

const { ccclass, property } = cc._decorator;

class KeyInterval {
	constructor(keyCode: number, interval: number) {
		this.keyCode = keyCode;
		this.interval = interval
	}
	public keyCode: number
	public interval: number
}

@ccclass
export default class KeyInput extends cc.Component {

	input: Map<number, boolean> = null;

	interval: number = 0;

	keyBuffer: KeyInterval[] = [];

	onLoad() {
		this.input = new Map();
	}

	start() {

		cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDown, this);
		cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.keyUp, this);
		//游戏进入后台时触发
		cc.game.on(cc.game.EVENT_HIDE, this._resetKey, this);
	}

	update(dt: number) {
		this.interval++;
		if (this.interval >= 60) {
			while (this.keyBuffer.length > 0) {
				let k = this.keyBuffer.pop();
				cc.log(k.interval + 'f ' + k.keyCode);
			}
		}

	}

	keyDown(key: cc.Event.EventKeyboard) {
		this.input.set(key.keyCode, true);
	}

	keyUp(key: cc.Event.EventKeyboard) {

		this.keyBuffer.push(new KeyInterval(key.keyCode, this.interval));
		cc.log(key.keyCode + ' ' + this.interval)

		this.input.set(key.keyCode, false);
		this.interval = 0;
		// this.scheduleOnce(() => {
		// 	let inter = this.keyBuffer.pop();
		// 	cc.log('~' + key.keyCode + ' ' + this.interval)
		// }, 1);
	}

	public getKey(key: number) {
		return this.input.get(key);
	}

	private _resetKey() {
		for (let pair of Object.keys(this.input)) {
			this.input[pair] = false;
			cc.log('reset' + pair);
		}
	}
}
